module.exports = options => {
  const jwt = require("jsonwebtoken");
  const AdminUser = require("../models/User");
  const assert = require('http-assert');
    const white = ["getsmsList", "setStatus", "queryAccountAll", "postSms", "uploadimg", "upload", "dyAll", "delVideo", "delVideoAll", "changeVideoStatus", "getVideo", "userSetVideo"]
  return async (req, res, next) => {
    let result = white.find(e => {
       return req.url.indexOf(e) != -1
    })
    if(result) {
      next();
    } else {
      const token = String(req.headers.authorization || '').split(' ').pop();
      assert(token, 401, '请先登录');
      let id // try{}里面使用let，也会形成块级作用域
      try {
        // jwt.verify() 验证错误会throw error
         id  = jwt.verify(token, req.app.get("secret")).id
      } catch (e) {
        assert(id, 401, "请先登录")
      } 
      req.user = await AdminUser.findById(id);
      assert(req.user, 401, '请先登录');
      next();
    }
    
  }
}